package com.axiang.lib_api;

import android.app.Application;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.axiang.lib_api.config.API;
import com.axiang.lib_api.http.cookie.CookieJarImpl;
import com.axiang.lib_api.http.cookie.store.PersistentCookieStore;
import com.axiang.lib_api.http.interceptor.BaseInterceptor;
import com.axiang.lib_api.http.interceptor.CacheInterceptor;
import com.axiang.lib_api.http.interceptor.logging.Level;
import com.axiang.lib_api.http.interceptor.logging.LoggingInterceptor;
import com.axiang.lib_api.utils.HttpsUtils;

import org.apache.http.conn.ssl.SSLSocketFactory;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Observable;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.ConnectionPool;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.internal.platform.Platform;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Description: <RetrofitManager><br>
 * Author:      mxdl<br>
 * Date:        2019/6/22<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class RetrofitManager {
    //超时时间
    private static final int DEFAULT_TIMEOUT = 20;
    //缓存时间
    private static final int CACHE_TIMEOUT = 10 * 1024 * 1024;

    private static OkHttpClient okHttpClient;
    private static Retrofit retrofit;

    private Cache cache = null;
    private File httpCacheDirectory;

    public static RetrofitManager retrofitManager;
    public static Context mContext;


    private RetrofitManager() {
        this(API.BASE_URL, null);
    }

    public static void init(Application application) {
        mContext = application;
    }

    private RetrofitManager(String url, Map<String, String> headers) {

        if (TextUtils.isEmpty(url)) {
            url = API.BASE_URL;
        }

        if (httpCacheDirectory == null) {
            httpCacheDirectory = new File(mContext.getCacheDir(), "axiang_cache");
        }

        try {
            if (cache == null) {
                cache = new Cache(httpCacheDirectory, CACHE_TIMEOUT);
            }
        } catch (Exception e) {
            Log.e("Could not create http", e + "");
        }
        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory();
        okHttpClient = new OkHttpClient.Builder()
                .cookieJar(new CookieJarImpl(new PersistentCookieStore(mContext)))
                //设置header
                .addInterceptor(new BaseInterceptor(headers))
                //设置缓存方式
                .cache(cache)
                .addInterceptor(new CacheInterceptor(mContext))
                .addNetworkInterceptor(new CacheInterceptor(mContext))
                //验证证书
                .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
                .hostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
                //打印日志
                .addInterceptor(new LoggingInterceptor
                        .Builder()//构建者模式
                        .loggable(BuildConfig.DEBUG) //是否开启日志打印
                        .setLevel(Level.BASIC) //打印的等级
                        .log(Platform.INFO) // 打印类型
                        .request("AxiangApiRequest") // request的Tag
                        .response("AxiangApiResponse")// Response的Tag
                        .build()
                )
                //设置超时时间
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool(8, 15, TimeUnit.SECONDS))
                // 这里你可以根据自己的机型设置同时连接的个数和时间，我这里8个，和每个保持时间为10s
                .build();

        retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(url)
                .build();
    }

    public static RetrofitManager getInstance() {
        if (retrofitManager == null) {
            synchronized (RetrofitManager.class) {
                if (retrofitManager == null) {
                    retrofitManager = new RetrofitManager();
                }
            }
        }
        return retrofitManager;
    }


    /**
     * 创建一个服务
     *
     * @return
     */
    public <T> T create(Class<T> service) {
        //确保多线程的情况下retrofit不为空或者被修改了
        if (retrofit == null) {
            throw new IllegalStateException("DEFAULT == null");
        }
        return retrofit.create(service);
    }

}